import { drawType } from './draw-type';
import * as Func from './comm-method';

const ns = 'http://www.w3.org/2000/svg';
//不需要转中横线连接的属性
const camelCaseIngore = ['textLength', 'lengthAdjust'];

export const draw = function (svgId, drawList, values, dataFunc, option) {
    let svgElement = document.getElementById(svgId);
    if (!svgElement) {
        return;
    }
    if (drawList.length === 0) {
        dataFunc();
    }
    fresh(svgElement, drawList, values);
    initGlobalEvent(svgElement, drawList, dataFunc, option, values);
    return svgElement;
};
export const refresh = function (svgElement, drawList, values) {
    fresh(svgElement, drawList, values);
};

function fresh(svgElement, drawList, values) {
    let children = svgElement.childNodes;
    let defaultEleArray = [];
    for (let i = 0; i < children.length; i++) {
        if(children[i].getAttribute){
            let id = children[i].getAttribute('id');
            if (id && id.includes('direct')) {
                defaultEleArray.push(children[i]);
            }
        }
    }
    svgElement.innerHTML = '';
    drawList.forEach((drawData, index) => {
        drawData.id = 'drawList' + index;
        //是否创建 g
        let containerEle = checkOrCreateG(svgElement, drawData);
        drawSvgUnderContainerEle(containerEle, drawData, values);
    });
    defaultEleArray.forEach((ele) => {
        svgElement.appendChild(ele);
    });
}

function initGlobalEvent(svgElement, drawList, dataFunc, option, values) {
    let totalScale = 1;
    let totalScaleMax = 16;
    let totalScaleMin = 0.25;
    let scale = 1;
    let cx = 0;
    let cy = 0;
    let mouseDown = false;
    let moveFromX = 0;
    let moveFromY = 0;
    let deltaX = 0;
    let deltaY = 0;
    let listeners;
    if (option) {
        listeners = option.listeners;
        if (option.totalScaleMax) {
            totalScaleMax = option.totalScaleMax;
        }
        if (option.totalScaleMin) {
            totalScaleMin = option.totalScaleMin;
        }
    }

    svgElement.onmousedown = (e) => {
        window.getSelection().empty();
        if (e.button === 0) {
            mouseDown = true;
            moveFromX = e.offsetX;
            moveFromY = e.offsetY;
        }
    };
    svgElement.onmouseout = () => {
        mouseDown = false;
        moveFromX = 0;
        moveFromY = 0;
    };
    svgElement.onmouseup = (e) => {
        mouseDown = false;
        moveFromX = 0;
        moveFromY = 0;
        if (e.button === 2) {
            if (listeners && listeners.includes('reset') && dataFunc) {
                totalScale = 1;
                totalScaleMax = 16;
                totalScaleMin = 0.25;
                scale = 1;
                cx = 0;
                cy = 0;
                deltaX = 0;
                deltaY = 0;
                if (option && option.totalScaleMax) {
                    totalScaleMax = option.totalScaleMax;
                }
                if (option && option.totalScaleMin) {
                    totalScaleMin = option.totalScaleMin;
                }
                drawList = dataFunc();
                fresh(svgElement, drawList, values);
            }
        }
    };
    if (listeners && listeners.includes('zoom')) {
        svgElement.onmousewheel = (e) => {
            if (e.deltaY > 0 && totalScale < totalScaleMax) {
                scale = 2;
            } else if (e.deltaY < 0 && totalScale > totalScaleMin) {
                scale = 0.5;
            } else {
                return;
            }
            cx = e.offsetX;
            cy = e.offsetY;
            totalScale *= scale;
            Func.zoom(drawList, { cx: cx, cy: cy, scale: scale, totalScale: totalScale });
            fresh(svgElement, drawList, values);
        };
    }
    //鼠标滑动
    svgElement.onmousemove = (event) => {
        if (mouseDown && listeners && listeners.includes('move')) {
            deltaX = event.offsetX - moveFromX;
            deltaY = event.offsetY - moveFromY;
            moveFromX = event.offsetX;
            moveFromY = event.offsetY;
            let checkMove = Func.move(drawList, { deltaX: deltaX, deltaY: deltaY });
            //moveData();
            if (checkMove) {
                fresh(svgElement, drawList, values);
            }
        }
    };
    svgElement.oncontextmenu = (event) => event.preventDefault();
}

//根据图形类型画图
function drawSvgUnderContainerEle(containerEle, drawData, values) {
    let drawList = drawData.children;
    if (!drawList || drawList.length === 0) {
        return;
    }
    drawList.forEach((drawParam, index) => {
        let nextContainer = checkOrCreateG(containerEle, drawParam);
        drawParam.id = drawData.id + '-' + index;
        //复制父级的 样式，文字样式
        if (!drawParam.isClearParentStyle) {
            drawParam.style = Object.assign({}, drawData.style, drawParam.style);
            drawParam.fontStyle = Object.assign({}, drawData.fontStyle, drawParam.fontStyle);
        }
        if (!drawParam.type) {
            drawParam.type = drawData.type;
        }
        drawSvg(nextContainer, drawParam, values);
    });
}
function drawSvg(parentEle, drawParam, values) {
    let drawEle;
    let attr = { ...drawParam.style };
    if (drawParam.checkStyle) {
        Object.assign(attr, drawParam.checkStyle({ drawParam: drawParam, values: values }));
    }
    if (drawParam.getPositionAttribute) {
        drawParam.getPositionAttribute(attr);
    }
    if (drawParam.type === drawType.RECT || drawParam.type === drawType.LIMIT) {
        drawEle = document.createElementNS(ns, 'rect');
    } else if (drawParam.type === drawType.TRIANGLE) {
        drawEle = document.createElementNS(ns, 'polygon');
    } else if (drawParam.type === drawType.LINE) {
        drawEle = document.createElementNS(ns, 'line');
    } else if (drawParam.type === drawType.CIRCLE) {
        drawEle = document.createElementNS(ns, 'circle');
    } else if (drawParam.type === drawType.ELLIPSE) {
        drawEle = document.createElementNS(ns, 'ellipse');
    } else if (drawParam.type === drawType.POLYGON) {
        drawEle = document.createElementNS(ns, 'polygon');
    } else if (drawParam.type === drawType.POLYLINE) {
        drawEle = document.createElementNS(ns, 'polyline');
    } else if (drawParam.type === drawType.TEXT) {
        //text不创建ele，下面统一创建
    } else if (drawParam.type === drawType.PATH) {
        drawEle = document.createElementNS(ns, 'path');
    } else if (drawParam.type === drawType.ARC) {
        drawEle = document.createElementNS(ns, 'path');
    } else if (drawParam.type === drawType.TABLE) {
        drawParam.id = drawParam.id + '_table';
        drawEle = document.createElementNS(ns, 'g');
        attr = {};
        let drawList = drawParam.getTableDrawList();
        drawEle.setAttribute('transform', 'translate(' + drawParam.start[0] + ',' + drawParam.start[1] + ')');
        //列表画图
        drawList.forEach((param) => {
            drawSvg(drawEle, param, values);
        });
    } else if(drawParam.type === drawType.IMAGE){
        drawEle = document.createElementNS(ns, 'image');
    }else{
        //其它图形
    }
    if (drawEle) {
        attr.id = drawParam.id;
        checkStrokeScale(attr, drawParam);
        setAttribute(attr, drawEle);
        setEventCallback(drawParam, drawEle);
        parentEle.appendChild(drawEle);
    }
    if (typeof drawParam.text !== 'undefined') {
        let textEle = drawText(drawParam.text, values, drawParam);
        setEventCallback(drawParam, textEle, drawEle);
        if (textEle) {
            parentEle.appendChild(textEle);
        }
    }
    drawSvgUnderContainerEle(parentEle, drawParam, values);
}

function checkStrokeScale(attr, drawParam) {
    let strokeWidth = attr.strokeWidth;
    let scale = drawParam.scale;

    if (strokeWidth && scale) {
        if (typeof drawParam.isBorderScale !== 'undefined' && !drawParam.isBorderScale) {
            attr.strokeWidth = strokeWidth / scale;
        }
    }
}
function setEventCallback(drawParam, ele, textParentEle) {
    if (drawParam.onClick) {
        ele.setAttribute('cursor', 'pointer');
        ele.onclick = (event) =>
            drawParam.onClick({ event: event, drawParam: drawParam, ele: ele, parentEle: textParentEle });
    }
    if (drawParam.onMouseover) {
        ele.onmouseover = (event) => {
            drawParam.onMouseover({ event: event, drawParam: drawParam, ele: ele, parentEle: textParentEle });
        };
    }
    if (drawParam.onMousemove) {
        ele.onmousemove = (event) => {
            drawParam.onMousemove({ event: event, drawParam: drawParam, ele: ele, parentEle: textParentEle });
        };
    }
    if (drawParam.onMouseout) {
        ele.onmouseout = (event) => {
            drawParam.onMouseout({ event: event, drawParam: drawParam, ele: ele, parentEle: textParentEle });
        };
    }
}

function drawText(text, values, drawParam) {
    let fontAttr = Func.getFontAttr(drawParam, values);
    let content;
    if (typeof text === 'number') {
        content = text + '';
    } else if (typeof text === 'string') {
        content = Func.findText(text, values);
    } else if (typeof text === 'object') {
        return drawText(text.text, values, drawParam);
    } else {
        console.error('没有处理的类型' + typeof text);
        return null;
    }
    let textEle = document.createElementNS(ns, 'text');
    fontAttr.id = drawParam.id + 'txt';
    checkFontScale(fontAttr, drawParam);
    setAttribute(fontAttr, textEle);
    textEle.innerHTML = content;
    return textEle;
}
function checkFontScale(fontAttr, drawParam) {
    if (typeof drawParam.isTextScale !== 'undefined' && !drawParam.isTextScale) {
        //todo 字体缩放
    }
}
function setAttribute(attrs, ele) {
    if(attrs.fill===''){
        attrs.fill = 'none';
    }
    for (let key in attrs) {
        ele.setAttribute(camelToLineJoin(key), attrs[key]);
    }
}
function camelToLineJoin(str) {
    if (camelCaseIngore.includes(str)) {
        return str;
    }
    return str.replace(/([A-Z])/g, (match, p1) => {
        return '-' + p1.toLowerCase();
    });
}

// 画全局的偏移及旋转标签 <g>
function checkOrCreateG(svgElement, drawData) {
    let returnEle = svgElement;
    if (drawData.translate) {
        let tx = drawData.translate[0];
        let ty = drawData.translate[1];
        let nextContainer = document.createElementNS(ns, 'g');
        nextContainer.setAttribute('transform', 'translate(' + tx + ',' + ty + ')');
        returnEle.appendChild(nextContainer);
        returnEle = nextContainer;
    }
    if (drawData.rotate) {
        let nextContainer = document.createElementNS(ns, 'g');
        nextContainer.setAttribute('transform', 'rotate(' + drawData.rotate + ')');
        returnEle.appendChild(nextContainer);
        returnEle = nextContainer;
    }
    if (drawData.scale && drawData.scale !== 1) {
        let nextContainer = document.createElementNS(ns, 'g');
        nextContainer.setAttribute('transform', 'scale(' + drawData.scale + ')');
        returnEle.appendChild(nextContainer);
        returnEle = nextContainer;
    }
    return returnEle;
}
